package com.example.prom.strategy.resttemplate;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;

public class GetUriRedirectStrategy extends DefaultRedirectStrategy {

    @Override
    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        boolean redirected = super.isRedirected(request, response, context);
        Header[] allHeaders = response.getAllHeaders();
        for (Header header : allHeaders) {
            if (StringUtils.equals(header.getName(), "Location")) {
                context.setAttribute("uri", header.getValue());
            }
        }
        Object uri = context.getAttribute("uri");
        response.setHeader("uri", String.valueOf(uri));
        return redirected;
    }
}
